package com.jfinal.club._admin.course;

import java.util.List;
import com.jfinal.club.common.model.Course;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

public class CourseAdminService {

	private Course dao = new Course().dao();
	
	public Page<Course> paginate(int pageNum) {
		return dao.paginate(pageNum, 10, "select course.id,course.cname,teacher.tname ", "from course left join teacher on course.tid=teacher.id order by course.id desc");
	}
	
	public boolean exists(int courseId, String name) {
		name = name.toLowerCase().trim();
		String sql = "select id from course where cname = ? and id != ? limit 1";
		Integer id = Db.queryInt(sql, name, courseId);
		return id != null;
	}
	
	public List<Course> getAll() {
		List<Course> list = dao.find("select * from course order by cname");
		return list;
	}
	
	public Ret save(int id, Course course) {
//		area.setId(id);
		course.setCname(course.getCname().trim());
		course.save();
		return Ret.ok("msg", "创建成功");
	}
	
	public Course edit(int id) {
		return dao.findById(id);
	}
	
	public Ret update(Course course) {
		if (exists(course.getId(), course.getCname())) {
			return Ret.fail("msg", "课程已经存在");
		}

		course.setCname(course.getCname().trim());
		course.update();
		return Ret.ok("msg", "修改成功");
	}
	
	public Ret delete(int courseId) {
		dao.deleteById(courseId);
		return Ret.ok("msg", "课程删除成功");
	}
}
